package com.longrise.android.byjk.plugins.tabfirst.revision.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.LEAP.Base.Objects.EntityBeanSet;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.plugins.tabfirst.news.NewsDetail2Activity;
import com.longrise.common.base.BaseActivity;
import com.longrise.common.base.BaseFragment;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.model.Insurace;
import com.longrise.android.byjk.plugins.tabfirst.revision.adapter.ConsultationAdapter;
import com.longrise.android.byjk.utils.Tracker_Google;
import com.longrise.android.byjk.widget.view.BBswipeRefreshLayout;
import com.longrise.android.byjk.widget.recyclerviewadapter.RecyclerOnScrollListener;
import com.longrise.common.datasource.remote.LoadDataManager;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by sujizhong on 2017/2/21.
 * 保险动态
 */
public class InsNewTopFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    private static final String TAG = "InsNewTopFragment";

    private RecyclerView mRecyclerView;
    private BBswipeRefreshLayout mSwipeLayout;
    private ConsultationAdapter mAdapter;
    private ImageView mImageTop;

    private boolean mClear;
    private int mPage = 1;
    private final int mPageSize = 10;
    private final int mPageType = 1;

    private boolean mDestory;
    private boolean mRefresh = true;

    @Override
    protected int getLayoutResourse(@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (savedInstanceState != null) {

        }
        return R.layout.fragment_insurancenewtop;
    }

    @Override
    public void initView() {
        Tracker_Google.getInstance().addGoogleScreenName("保险动态");
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();
        onEvent();
    }

    private void init() {
        mRecyclerView = (RecyclerView) getView().findViewById(R.id.recyclerview_ins);
        mRecyclerView.addOnScrollListener(mOnScrollListener);
        mSwipeLayout = (BBswipeRefreshLayout) getView().findViewById(R.id.swipelayout_ins);
        mImageTop = (ImageView) getView().findViewById(R.id.iv_top);
        mSwipeLayout.setOnRefreshListener(this);
        setRecyclerViewLayoutManager();
        adapter();

        if (checkNetWorkEnable()) {
            mClear = true;
            mPage = 1;
            mSwipeLayout.setRefreshing(true);
            request();
        }
    }

    private void onEvent() {
        if (mImageTop != null) {
            mImageTop.setOnClickListener(mListener);
        }
    }

    private View.OnClickListener mListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.iv_top) {
                v.post(new Runnable() {
                    @Override
                    public void run() {
                        mRecyclerView.scrollToPosition(0);
                    }
                });
            }
        }
    };

    private RecyclerOnScrollListener mOnScrollListener = new RecyclerOnScrollListener() {
        @Override
        public void onLoadListener() {
            if (checkNetWorkEnable()) {
                mPage++;
                mClear = false;
                request();
            }
        }

        @Override
        public void onScrollStatus(boolean enable) {
            mSwipeLayout.setEnabled(enable);
//            mImageTop.setVisibility(enable ? View.GONE : View.VISIBLE);
        }
    };

    private void adapter() {
        mAdapter = new ConsultationAdapter((BaseActivity) getActivity()) {

            @Override
            public void onItemClickListener(int position, Insurace insurace) {
                String url = insurace.linkurl;
                Intent newIntent = new Intent(getContext(), NewsDetail2Activity.class);
                newIntent.putExtra(NewsDetail2Activity.EXTRA_NEW_URL, url);
                startActivityForResult(newIntent, 100);
            }
        };
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && data != null) {
        }
    }

    private void setRecyclerViewLayoutManager() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
    }

    private void request() {
        EntityBean bean = new EntityBean();
        bean.set("pageNum", mPage);
        bean.set("pageSize", mPageSize);
        EntityBean reqBean = new EntityBean();
        reqBean.set("bean", bean);
        commit(reqBean, "bbt_news_sNewsListNew");
    }

    private void commit(final EntityBean reqBean, String api) {
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl, api, reqBean, mOnRequestCallListener);
    }

    private LoadDataManager.OnRequestCallListener mOnRequestCallListener = new LoadDataManager.OnRequestCallListener() {

        @Override
        public void onSuccess(String key, String service, Object result) {
            try {
                if (mDestory) return;
                EntityBean resultBean = (EntityBean) result;
                EntityBeanSet resultSet = (EntityBeanSet) resultBean.get("result");
                if (resultSet != null) {
                    parse(resultSet);
                } else {
                    if (mPage <= 1) {
                        showSnackBar("未查询到相关数据");
                    } else {
                        if (mRefresh) {
                            showSnackBar("已经是最后一条");
                            mRefresh = false;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
            if (mDestory) return;
            showToast(getString(R.string.nonetwork));
        }

        @Override
        public void onFinished(String key, String service) {
            if (mOnScrollListener != null) {
                mOnScrollListener.reset();
            }
            if (mSwipeLayout != null) {
                mSwipeLayout.setRefreshing(false);
            }
        }
    };

    private void parse(EntityBeanSet resultSet) throws Exception {
        if (mClear && mAdapter != null) {
            mAdapter.clear();
        }
        int size = resultSet.getSize();
        List<Insurace> insuraces = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            EntityBean itemBean = resultSet.get(i);
            Insurace insurace = new Insurace();
            insurace.id = itemBean.getString("id");
            insurace.title = itemBean.getString("title");
            insurace.createtime = itemBean.getString("createtime");
            insurace.newfrom = itemBean.getString("newfrom");
            insurace.newspic = itemBean.getString("newspic");
            insurace.reviewnum = itemBean.getString("reviewnum");
            insurace.reviewnumstr = itemBean.getString("reviewnumstr");
            insurace.linkurl = itemBean.getString("linkurl");
            insuraces.add(insurace);
        }
//        List<Insurace> insurances = JsonUtil.fromJson(new JSONObject("", new TypeToken<List<Insurace>>() {
//        }.getType());
        if (mAdapter != null) {
            mAdapter.addAll(insuraces);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mDestory = true;
    }

    @Override
    public void onRefresh() {
        if (checkNetWorkEnable()) {
            mRefresh = true;
            mPage = 1;
            mClear = true;
            request();
            mOnScrollListener.reset();
        }else{
            mSwipeLayout.setRefreshing(false);
        }
    }
}
